var citys = require('../../../../../utils/address.js')
var DateUtil = require('../../../../../utils/DateUtil.js')
var animation
Page({

  /**
   * 页面的初始数据
   */
  data: {
    default: false,
    selectedTag: 0,
    address: {
      consignee: '', phone: '', detailed: '', province: '', city: '', country_name: '中国', country: '100000', type: '',
      district: '', select: false, area_code: '+86', city_name: '', district_name: '', province_name: '', default_state: '1', id: ''
    }, //备份数据
    animationAddressMenu: {},
    addressMenuIsShow: false,
    value: [0, 0, 0],
    provinces: [],
    citys: [],
    areas: [],
    areaInfo: '',
    type:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.type=='add'){  //新增地址判断
      citys.provinces().then((res) => {
        this.setData({
          provinces: res.children[0].children,
          citys: res.children[0].children[0].children,
          areas: res.children[0].children[0].children[0].children,
          type: options.type
        })
      })
    }
    if (options.type == 'edit'){ //编辑地址判断
      wx.showLoading({
        title: '正在加载...',
      })
      var editAddress = wx.getStorageSync('editAddress')
      editAddress.default_state = editAddress.address_id?'0':'1'
      citys.provinces().then((res) => {
        this.setData({
          provinces: res.children[0].children,
          citys: res.children[0].children[0].children,
          areas: res.children[0].children[0].children[0].children,
          address: editAddress,
          type: options.type,
          areaInfo: editAddress.province_name + editAddress.city_name + editAddress.district_name
        })
        wx.hideLoading()
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  /**
   * 设置默认地址
   */
  setDefaultAddress: function () {
    var address = this.data.address
    address.default_state = this.data.address.default_state=='0'?'1':'0'
    this.setData({
      address: address
    })
  },
  //选择地址
  addNewAddress:function(){
    this.setData({
      addressMenuIsShow: true
    })
  },
  //填写联系人
  addressName:function(e){
    let self=this
    let address = self.data.address
    address.consignee=e.detail.value
    // self.setData({
    //   address: address
    // })
  },
  //删除联系人姓名
  delAddressName:function(e){
    let self = this
    let address = self.data.address
    address.consignee = ''
    self.setData({
      address: address
    })
  },
  //填写联系人电话
  addressPhone: function (e) {
    let self = this
    let address = self.data.address
    address.phone = e.detail.value
    // self.setData({
    //   address: address
    // })
  },
  //删除联系人电话
  delAddressPhone: function (e) {
    let self = this
    let address = self.data.address
    address.phone = ''
    self.setData({
      address: address
    })
  },
  //填写详细地址
  addressDetail: function (e) {
    let self = this
    let address = self.data.address
    address.detailed = e.detail.value
    // self.setData({
    //   address: address
    // })
  },
  //保存地址
  saveAddress: function () {
    let self=this
    var dateTime = new Date()
    var address = self.data.address
    address.update_time = DateUtil.dateToStr('', dateTime)
    address.default_state
    self.setData({
      address: address
    })
    if (!address.consignee) {
      wx.showToast({
        title: '请填写收货人',
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return
    }
    if (address.consignee.length > 11) {
      wx.showToast({
        title: '收货人名字过长',
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return
    }
    if (!/^1(3|4|5|7|8)\d{9}$/.test(address.phone)) {
      wx.showToast({
        title: '请填写正确的号码',
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return
    }
    if (!address.phone) {
      wx.showToast({
        title: '请填写联系电话',
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return
    }
    if (!address.province || !address.city || !address.district) {
      wx.showToast({
        title: '请选择省市区',
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return
    }
    if (!address.detailed) {
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return
    }
    if(self.data.type=='add'){
      wx.request({
        url: wx.envConfig.host + '/user/insertUserAddress?cookiez=' + wx.getStorageSync('cookiez'),
        data: JSON.stringify(self.data.address),
        method: 'POST',
        success: function (res) {
          if (res.data.error_code === "Y10000") {
            wx.navigateBack()
          }
        },
        fail: function ({ errMsg }) {
          console.log('request fail', errMsg)
        }
      })
    }
    if (self.data.type == 'edit') {
      wx.request({
        url: wx.envConfig.host + '/user/updateUserAddressById?cookiez=' + wx.getStorageSync('cookiez'),
        data: JSON.stringify(self.data.address), 
        method: 'POST',
        success: function (res) {
          if (res.data.error_code === "Y10000") {
            wx.navigateBack()
          }
        },
        fail: function ({ errMsg }) {
          console.log('request fail', errMsg)
        }
      })
    }
  },
  /**
   * 删除地址
   */
  deleteAddress: function (e) {
    var self = this
    var id = self.data.address.id
    wx.showModal({
      title: '提示',
      content: '确定删除该地址？',
      cancelText: '否',
      cancelColor: '#4825BF',
      confirmText: '是',
      confirmColor: '#4825BF',
      success: function (res) {
        if (res.confirm) {
          if(self.data.type=='edit'){
            self.deleteUserAddress(id)
          }else{
            wx.navigateBack()
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //删除地址
  deleteUserAddress: function (addressId) {
    let self = this
    wx.request({
      url: wx.envConfig.host + '/user/deleteUserAddressById?params=' + JSON.stringify({ id: addressId }) + '&cookiez=' + wx.getStorageSync('cookiez'),
      method: 'POST',
      success: function (ress) {
        if (ress.data.error_code === "Y10000") {
          wx.navigateBack()
        }
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
      }
    })
  },
  /**
   * 选择标签
   */
  selectTags: function (event) {
    let self = this
    let address = self.data.address
    address.type = event.currentTarget.dataset.type
    this.setData({
      address: address
    })
  },
  // 点击所在地区弹出选择框
  selectDistrict: function (e) {
    var that = this
    // 如果已经显示，不在执行显示动画
    if (that.data.addressMenuIsShow) {
      return
    }
    // 执行显示动画
    that.startAddressAnimation(true)
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    console.log(isShow)
    var that = this
    if (isShow) {
      that.animation.translateY(0 + 'rpx').step()
    } else {
      that.animation.translateY(540 + 'rpx').step()
    }
    that.setData({
      animationAddressMenu: that.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  // 点击地区选择取消按钮
  cityCancel: function (e) {
    this.setData({
      addressMenuIsShow: false,
    })
  },
  // 点击地区选择确定按钮
  citySure: function (e) {
    var that = this
    var city = that.data.city
    var value = that.data.value
    // that.startAddressAnimation(false)
    // 将选择的城市信息显示到输入框
    let address = that.data.address
    address.province = that.data.provinces[value[0]].id
    address.city = that.data.citys[value[1]].id
    address.district = that.data.areas[value[2]].id
    address.province_name = that.data.provinces[value[0]].name
    address.city_name = that.data.citys[value[1]].name
    address.district_name = that.data.areas[value[2]].name
    that.setData({
      address: address,
      addressMenuIsShow:false,
      areaInfo: address.province_name + address.city_name + address.district_name
    })

  },
  // 点击蒙版时取消组件的显示
  hideCitySelected: function (e) {
    console.log(e)
    this.startAddressAnimation(false)
  },
  // 处理省市县联动逻辑
  cityChange: function (e) {
    console.log(e)
    let self=this
    var value = e.detail.value
    var provinces = this.data.provinces
    var citys = this.data.citys
    var areas = this.data.areas
    var provinceNum = value[0]
    var cityNum = value[1]
    var countyNum = value[2]
    // debugger
    // 如果省份选择项和之前不一样，表示滑动了省份，此时市默认是省的第一组数据，
    if (self.data.value[0] != provinceNum) {
      for (let i = 0; i < self.data.provinces.length; i++) {
        if (provinceNum == i ) { //如果数据中的省份Id跟选中的省份id相等
          var citysList = self.data.provinces[i].children
          self.setData({
            value: [provinceNum, 0, 0],
            citys: citysList,
            areas: citysList[0].children
          })
        }
      }
    } else if (self.data.value[1] != cityNum) {
      // 滑动选择了第二项数据，即市，此时区显示省市对应的第一组数据
      for (let i = 0; i < self.data.citys.length; i++) {
        if (cityNum == i) { //如果数据中的省份Id跟选中的省份id相等
          var areasList = self.data.citys[i].children
          self.setData({
            value: [provinceNum, cityNum, 0],
            areas: areasList
          })
        }
      }
    } else {
      // 滑动选择了区
      self.setData({
        value: [provinceNum, cityNum, countyNum]
      })
    }
    console.log(self.data)
  },
})